﻿#include "Mutex.h"

namespace sky
{
    // 互斥量
    Mutex::Mutex(bool)
    {
        ::InitializeCriticalSection(&m_cs);
    #ifdef SKY_DEBUG
        file = 0, line = 0;
    #endif
    }

    Mutex::~Mutex()
    {
        ::DeleteCriticalSection(&m_cs);
    }

#ifdef SKY_DEBUG
    void Mutex::Lock(const char * f, int l)
    {
        ::EnterCriticalSection(&m_cs);
        file = f;
        line = l;
    }

    void Mutex::UnLock()
    {
        ::LeaveCriticalSection(&m_cs);
        file = (const char *)0xaabbccdd;
        line = 0x12345678;
    }

#else
    void Mutex::Lock()
    {
        ::EnterCriticalSection(&m_cs);
    }

    void Mutex::UnLock()
    {
        ::LeaveCriticalSection(&m_cs);
    }
#endif

    // 信号量
    Semaphore::Semaphore(int initCount)
    {
        m_h = ::CreateSemaphore(NULL, initCount, 0x7FFFFFFF, NULL);
    }

    Semaphore::~Semaphore()
    {
        if (m_h)
        {
            ::CloseHandle(m_h);
        }
    }

    bool Semaphore::Wait(unsigned long timeOut)
    {
        unsigned ret = ::WaitForSingleObject(m_h, timeOut);
        if (ret == WAIT_OBJECT_0)
            return true;

        return false;
    }

    void Semaphore::Post()
    {
        ::ReleaseSemaphore(m_h, 1, NULL);
    }

    // 守卫
    // 临界区线程安全自动保护
} // namespace sky